﻿using System;
using System.Collections.Generic;
using PreeRegisterModel;
using Newtonsoft.Json.Linq;
using System.Data;

namespace PreeRegisterBLL
{
    public class CostBLL
    {
        #region 长治和平接口 费用清单查询

        /// <summary>
        /// 长治和平 费用清单查询
        /// </summary>
        /// <param name="notPayRequestModel"></param>
        /// <returns></returns>
        public static CostListResponseModel GetCostList(CostListRequestModel costListRequestModel)
        {
            //费用清单查询
            CostListResponseModel costListResponseModel = new CostListResponseModel();

            //item 
            List<CostListResponseItemModel> CostListResponseModel_list = new List<CostListResponseItemModel>();

            try
            {
                string times = string.Empty;
                string adnum = CommonBLL.GetAdnum(costListRequestModel.pid, out times);
                hars_costlist bll_costlist = new hars_costlist();
                // CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, "查询本地数据开始1：" + DateTime.Now);
                DataSet ds_costlist = null;// bll_costlist.GetList(costListRequestModel.pid, costListRequestModel.time);
                                           // CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, "查询本地数据结束1：" + DateTime.Now);
                if (ds_costlist == null || ds_costlist.Tables[0].Rows.Count <= 0)
                {
                    int errorcount = AddCostListInfo(adnum, times, "", "");//调用接口获取费用清单，并入库
                    if (errorcount > 0)
                    {
                        costListResponseModel.code = "0";//code
                        costListResponseModel.msg = "费用清单处理失败，失败数量：" + errorcount;//msg
                        return costListResponseModel;
                    }
                }

                CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, "查询本地数据开始2：" + DateTime.Now);
                ds_costlist = bll_costlist.GetList(costListRequestModel.pid, costListRequestModel.time);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, "查询本地数据结束2：" + DateTime.Now);
                if (ds_costlist != null && ds_costlist.Tables[0].Rows.Count > 0)
                {
                    DataView dataView = ds_costlist.Tables[0].DefaultView;
                    DataTable dataDays = dataView.ToTable(true, "days");
                    costListResponseModel.code = "1";//code
                    costListResponseModel.msg = "获取费用清单信息成功。";//msg
                    costListResponseModel.hospid = CommonBLL.GetConfig("hospitalid");//医院ID
                    costListResponseModel.pid = costListRequestModel.pid;//患者ID
                    for (int i = 0; i < dataDays.Rows.Count; i++)
                    {
                        CostListResponseItemModel costListResponseItemModel = new CostListResponseItemModel();
                        costListResponseItemModel.time = dataDays.Rows[i]["days"].ToString();
                        CostListResponseTitleModel costListResponseTitleModel = new CostListResponseTitleModel();
                        costListResponseTitleModel.count = "数量";
                        costListResponseTitleModel.name = "品名";
                        costListResponseTitleModel.spec = "规格";
                        costListResponseTitleModel.sum = "金额";
                        costListResponseTitleModel.ext1 = "扩展1";
                        costListResponseTitleModel.ext2 = "扩展2";
                        costListResponseItemModel.title = costListResponseTitleModel;

                        DataTable dt_oneday = GetCostList_OneDay(ds_costlist.Tables[0], costListResponseItemModel.time);
                        List<CostListResponseContentModel> CostListResponseContentModel_list = new List<CostListResponseContentModel>();
                        for (int j = 0; j < dt_oneday.Rows.Count; j++)
                        {
                            costListResponseItemModel.total = dt_oneday.Rows[j]["total"].ToString();
                            CostListResponseContentModel costListResponseContentModel = new CostListResponseContentModel();
                            costListResponseContentModel.count = dt_oneday.Rows[j]["Count"].ToString();
                            costListResponseContentModel.ext1 = "";
                            costListResponseContentModel.ext2 = "";
                            costListResponseContentModel.id = dt_oneday.Rows[j]["Id"].ToString();
                            costListResponseContentModel.name = dt_oneday.Rows[j]["FeeName"].ToString();
                            costListResponseContentModel.spec = dt_oneday.Rows[j]["Specification"].ToString();
                            costListResponseContentModel.sum = CommonBLL.GetAmount(dt_oneday.Rows[j]["Amount"].ToString());
                            DateTime dt = Convert.ToDateTime(dt_oneday.Rows[j]["FeeDateTime"].ToString());
                            costListResponseContentModel.time = dt.ToString("yyyy-MM-dd HH:mm:ss");
                            CostListResponseContentModel_list.Add(costListResponseContentModel);
                        }
                        costListResponseItemModel.content = CostListResponseContentModel_list;
                        CostListResponseModel_list.Add(costListResponseItemModel);
                    }
                    costListResponseModel.item = CostListResponseModel_list;
                }
                else
                {
                    costListResponseModel.code = "1";//code
                    costListResponseModel.msg = string.Format("查询费用清单信息成功，病人截止到{0}前，无费用信息"
                        , DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));//msg
                }
            }

            catch (Exception err)
            {
                throw err;
            }
            return costListResponseModel;
        }

        public static CostTotalResponseModel GetCostTotal(CostTotalRequestModel costTotalRequestModel)
        {
            //费用汇总查询
            CostTotalResponseModel costTotalResponseModel = new CostTotalResponseModel();

            //item 
            // List<CostTotalResponseItemModel> CostTotalResponseModel_list = new List<CostTotalResponseItemModel>();
            CostTotalResponseItemModel CostTotalResponseModel = new CostTotalResponseItemModel();
            try
            {
                string times = string.Empty;
                string adnum = CommonBLL.GetAdnum(costTotalRequestModel.pid, out times);

                hars_costlist bll_costlist = new hars_costlist();
                hars_costtotal bll_costtotal = new hars_costtotal();

                int errorcount = InitCostTotalInfo(adnum, times);//调用接口获取费用汇总，并入库,不存在新增，存在修改
                if (errorcount > 0)
                {
                    costTotalResponseModel.code = "0";//code
                    costTotalResponseModel.msg = "费用汇总处理失败";//msg
                    return costTotalResponseModel;
                }
                DataSet ds_costtotal = bll_costtotal.GetListByPid(costTotalRequestModel.pid);
                if (ds_costtotal != null && ds_costtotal.Tables[0].Rows.Count > 0)
                {
                    costTotalResponseModel.code = "1";//code
                    costTotalResponseModel.msg = "获取费用汇总信息成功。";//msg
                    costTotalResponseModel.cid = ds_costtotal.Tables[0].Rows[0]["uid"].ToString().Trim();//费用汇总ID 用中间表的主键
                    costTotalResponseModel.tprice = CommonBLL.GetAmount(ds_costtotal.Tables[0].Rows[0]["TotalMoney"].ToString().Trim());//费用总额   
                    costTotalResponseModel.cash = CommonBLL.GetAmount(ds_costtotal.Tables[0].Rows[0]["TotalPrepayMoney"].ToString().Trim());//押金 （单位：元）
                    costTotalResponseModel.dbcash = CommonBLL.GetAmount(ds_costtotal.Tables[0].Rows[0]["LeftDeposit"].ToString().Trim());//押金结余（单位：元）
                    costTotalResponseModel.state = ds_costtotal.Tables[0].Rows[0]["PatientType"].ToString().Trim();//医保审核状态
                    costTotalResponseModel.time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //DateTime.Now.AddDays(0).ToString("yyyy-MM-dd") + " 23:59:59";//截止时间
                    costTotalResponseModel.copay = ""; //统筹支付（单位：元）
                    costTotalResponseModel.hctprice = "";// 医保本年累计缴费金额 （单位：元）
                    costTotalResponseModel.ownpay = "";//自付（单位：元）

                    for (int i = 0; i < ds_costtotal.Tables[0].Rows.Count; i++)
                    {
                        CostTotalResponseItemModel costTotalResponseItemModel = new CostTotalResponseItemModel();
                        List<CostTotalResponseTitleModel> costTotalResponseTitleModel_list = new List<CostTotalResponseTitleModel>();
                        CostTotalResponseTitleModel costTotalResponseTitleModel = new CostTotalResponseTitleModel();
                        costTotalResponseTitleModel.name = "名称";
                        costTotalResponseTitleModel.sum = "金额";
                        costTotalResponseTitleModel.ext1 = "扩展1";
                        costTotalResponseTitleModel_list.Add(costTotalResponseTitleModel);
                        costTotalResponseItemModel.title = costTotalResponseTitleModel_list;

                        DataSet ds_costdetail = bll_costlist.GetCostDetial(costTotalRequestModel.pid, "");
                        List<CostTotalResponseContentModel> CostTotalResponseContentModel_list = new List<CostTotalResponseContentModel>();
                        for (int j = 0; j < ds_costdetail.Tables[0].Rows.Count; j++)
                        {
                            CostTotalResponseContentModel costTotalResponseContentModel = new CostTotalResponseContentModel();
                            costTotalResponseContentModel.ext1 = "";
                            costTotalResponseContentModel.name = ds_costdetail.Tables[0].Rows[j]["FeeName"].ToString();
                            costTotalResponseContentModel.sum = CommonBLL.GetAmount(ds_costdetail.Tables[0].Rows[j]["Amount"].ToString());
                            CostTotalResponseContentModel_list.Add(costTotalResponseContentModel);
                        }
                        CostTotalResponseModel.title = costTotalResponseTitleModel_list;
                        CostTotalResponseModel.content = CostTotalResponseContentModel_list;
                    }
                    costTotalResponseModel.item = CostTotalResponseModel;
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            //返回
            return costTotalResponseModel;
        }


        /// <summary>
        /// 费用清单拉取 入库操作
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <param name="prescriptionCode">处方编号 可空</param>
        /// <param name="adviceIdList">医嘱Id 可空</param>
        /// <returns></returns>
        public static int AddCostListInfo(string patientCode, string hospitalizedTimes, string prescriptionCode, string adviceIdList)
        {
            int success_count = 0;
            int error_count = 0;
            int repeat_count = 0;

            ParentInfoRequestModel parentInfoRequestModel = new ParentInfoRequestModel();
            try
            {
                JObject obj_costlist = ChangZhiHePingBLL.GetInhospitalPatientFeeDetailInfo(patientCode, hospitalizedTimes, prescriptionCode, adviceIdList);//获取费用明细
                string code_costlist = obj_costlist["code"].ToString();
                if (string.Equals(code_costlist, "1"))
                {
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, "获取费用清单成功，清单报文长度：\r\n" + obj_costlist.ToString().Length);
                    hars_costlist bll_costlist = new hars_costlist();
                    var mJObj_costlist = JArray.Parse(obj_costlist["result"].ToString());
                    foreach (var dr_costlist in mJObj_costlist)
                    {
                        PreeRegisterModel.hars_costlist model_costlist = new PreeRegisterModel.hars_costlist();
                        model_costlist.AdviceId = dr_costlist["AdviceId"] == null ? "" : dr_costlist["AdviceId"].ToString().Trim();
                        model_costlist.Amount = dr_costlist["Amount"] == null ? "" : dr_costlist["Amount"].ToString().Trim();//
                        model_costlist.ApplicationCode = dr_costlist["ApplicationCode"] == null ? "" : dr_costlist["ApplicationCode"].ToString().Trim();//
                        model_costlist.BatchCode = dr_costlist["BatchCode"] == null ? "" : dr_costlist["BatchCode"].ToString().Trim();//
                        model_costlist.BelongDeptCode = dr_costlist["BelongDeptCode"] == null ? "" : dr_costlist["BelongDeptCode"].ToString().Trim();//
                        model_costlist.BelongDeptName = dr_costlist["BelongDeptName"] == null ? "" : dr_costlist["BelongDeptName"].ToString().Trim();//
                        model_costlist.Count = dr_costlist["Count"] == null ? "" : dr_costlist["Count"].ToString().Trim();//
                        model_costlist.createdate = DateTime.Now;
                        model_costlist.DrugStoreCode = dr_costlist["DrugStoreCode"] == null ? "" : dr_costlist["DrugStoreCode"].ToString().Trim();//
                        model_costlist.DrugStoreName = dr_costlist["DrugStoreName"] == null ? "" : dr_costlist["DrugStoreName"].ToString().Trim();//
                        model_costlist.FeeCode = dr_costlist["FeeCode"] == null ? "" : dr_costlist["FeeCode"].ToString().Trim();//
                        model_costlist.FeeDateTime = dr_costlist["FeeDateTime"] == null ? "" : dr_costlist["FeeDateTime"].ToString().Trim();//
                        model_costlist.FeeName = dr_costlist["FeeName"] == null ? "" : dr_costlist["FeeName"].ToString().Trim();//
                        model_costlist.FirstItemCode = dr_costlist["FirstItemCode"] == null ? "" : dr_costlist["FirstItemCode"].ToString();//
                        model_costlist.HospitaliezdTimes = dr_costlist["HospitaliezdTimes"] == null ? "" : dr_costlist["HospitaliezdTimes"].ToString();//
                        model_costlist.Id = dr_costlist["Id"] == null ? "" : dr_costlist["Id"].ToString();//
                        model_costlist.OpenDeptCode = dr_costlist["OpenDeptCode"] == null ? "" : dr_costlist["OpenDeptCode"].ToString().Trim();//
                        model_costlist.OpenDeptName = dr_costlist["OpenDeptName"] == null ? "" : dr_costlist["OpenDeptName"].ToString().Trim();//
                        model_costlist.OpenDoctorCode = dr_costlist["OpenDoctorCode"] == null ? "" : dr_costlist["OpenDoctorCode"].ToString().Trim();//
                        model_costlist.OpenDoctorName = dr_costlist["OpenDoctorName"] == null ? "" : dr_costlist["OpenDoctorName"].ToString().Trim();//
                        model_costlist.OperatorCode = dr_costlist["OperatorCode"] == null ? "" : dr_costlist["OperatorCode"].ToString().Trim();//
                        model_costlist.OperatorName = dr_costlist["OperatorName"] == null ? "" : dr_costlist["OperatorName"].ToString().Trim();//
                        model_costlist.PatientCode = dr_costlist["PatientCode"] == null ? "" : dr_costlist["PatientCode"].ToString().Trim();//
                        model_costlist.PatientName = dr_costlist["PatientName"] == null ? "" : dr_costlist["PatientName"].ToString().Trim();//
                        model_costlist.PrescriptionCode = dr_costlist["PrescriptionCode"] == null ? "" : dr_costlist["PrescriptionCode"].ToString().Trim();//
                        model_costlist.Price = dr_costlist["Price"] == null ? "" : dr_costlist["Price"].ToString().Trim();//
                        model_costlist.ReceiveDeptCode = dr_costlist["ReceiveDeptCode"] == null ? "" : dr_costlist["ReceiveDeptCode"].ToString().Trim();//
                        model_costlist.ReceiveDeptName = dr_costlist["ReceiveDeptName"] == null ? "" : dr_costlist["ReceiveDeptName"].ToString().Trim();//
                        model_costlist.ReceiveDoctorCode = dr_costlist["ReceiveDoctorCode"] == null ? "" : dr_costlist["ReceiveDoctorCode"].ToString().Trim();//
                        model_costlist.RefundDatetime = dr_costlist["RefundDatetime"] == null ? "" : dr_costlist["RefundDatetime"].ToString().Trim();//
                        model_costlist.RefundOperatorCode = dr_costlist["RefundOperatorCode"] == null ? "" : dr_costlist["RefundOperatorCode"].ToString().Trim();//
                        model_costlist.RefundOperatorName = dr_costlist["RefundOperatorName"] == null ? "" : dr_costlist["RefundOperatorName"].ToString().Trim();//
                        model_costlist.RefundReason = dr_costlist["RefundReason"] == null ? "" : dr_costlist["RefundReason"].ToString().Trim();//
                        model_costlist.Specification = dr_costlist["Specification"] == null ? "" : dr_costlist["Specification"].ToString().Trim();//
                        model_costlist.TradePrice = dr_costlist["TradePrice"] == null ? "" : dr_costlist["TradePrice"].ToString().Trim();//
                        model_costlist.Unit = dr_costlist["Unit"] == null ? "" : dr_costlist["Unit"].ToString().Trim();//
                        model_costlist.pid = CommonBLL.GetPid(model_costlist.PatientCode, model_costlist.HospitaliezdTimes);
                        try
                        {
                            if (!string.IsNullOrEmpty(model_costlist.Id))
                            {
                                if (!bll_costlist.Exists(model_costlist.Id))
                                {
                                    if (bll_costlist.Add(model_costlist))
                                    {
                                        success_count++;
                                        //CommonBLL.WriteLog(string.Format("\r\n费用清单操作成功，患者ID：{0},医院侧费用清单ID：{1}"
                                        //    , model_costlist.pid, model_costlist.Id));
                                    }
                                    else
                                    {
                                        error_count++;
                                        //CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用清单入库失败，患者ID：{0},医院侧费用清单ID：{1}"
                                        //     , model_costlist.pid, model_costlist.Id));
                                    }
                                }
                                else
                                {
                                    repeat_count++;
                                    //CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用清单信息数据重复，忽略处理，患者ID：{0},医院侧费用清单ID：{1}"
                                    //    , model_costlist.pid, model_costlist.Id));

                                }
                            }
                            else
                            {
                                CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用清单数据异常，ID为空。患者ID：{0}"
                          , model_costlist.pid));
                            }

                        }
                        catch (Exception ex)
                        {
                            error_count++;
                            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用清单信息入库异常，患者ID：{0},医院侧费用清单ID：{1}。失败原因{2}"
                                , model_costlist.pid, model_costlist.Id, ex.Message));
                            continue;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return error_count;
        }

        /// <summary>
        /// 费用汇总拉取 入库操作
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <returns></returns>
        public static int InitCostTotalInfo(string patientCode, string hospitalizedTimes)
        {
            int success_count = 0;
            int error_count = 0;

            ParentInfoRequestModel parentInfoRequestModel = new ParentInfoRequestModel();
            try
            {
                JObject obj_costtotal = ChangZhiHePingBLL.GetInhospitalPatientTotalFeeInfo(patientCode, hospitalizedTimes);//获取费用汇总
                string code_costtotal = obj_costtotal["code"].ToString();
                if (string.Equals(code_costtotal, "1"))
                {
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, "获取费用汇总成功：\r\n" + CommonBLL.ConvertJsonString(obj_costtotal.ToString()));
                    hars_costtotal bll_costtotal = new hars_costtotal();
                    var mJObj_costlist = JArray.Parse(obj_costtotal["result"].ToString());
                    foreach (var dr_costlist in mJObj_costlist)
                    {
                        PreeRegisterModel.hars_costtotal model_costtotal = new PreeRegisterModel.hars_costtotal();
                        model_costtotal.createdate = DateTime.Now;
                        model_costtotal.HospitaliezdTimes = hospitalizedTimes;//
                        model_costtotal.LeftDeposit = dr_costlist["LeftDeposit"] == null ? "" : dr_costlist["LeftDeposit"].ToString().Trim();//
                        model_costtotal.PatientCode = patientCode;//
                        model_costtotal.PatientType = dr_costlist["PatientType"] == null ? "" : dr_costlist["PatientType"].ToString().Trim();//
                        model_costtotal.Tips = dr_costlist["Tips"] == null ? "" : dr_costlist["Tips"].ToString().Trim();//
                        model_costtotal.TotalMoney = dr_costlist["TotalMoney"] == null ? "" : dr_costlist["TotalMoney"].ToString().Trim();//
                        model_costtotal.TotalPrepayMoney = dr_costlist["TotalPrepayMoney"] == null ? "" : dr_costlist["TotalPrepayMoney"].ToString().Trim();//
                        model_costtotal.pid = CommonBLL.GetPid(model_costtotal.PatientCode, model_costtotal.HospitaliezdTimes);

                        try
                        {
                            //存在，将老的记录state状态更新为2.新增一条状态为1的记录
                            DataSet ds_costtotal = bll_costtotal.GetListByPid(model_costtotal.pid);
                            if (ds_costtotal.Tables[0].Rows.Count > 0)
                            {
                                if (bll_costtotal.UpdateState(ds_costtotal.Tables[0].Rows[0]["pid"].ToString(), 2))
                                {
                                    success_count++;
                                    CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用汇总状态更新成功，患者ID：{0}", model_costtotal.pid));
                                }
                                else
                                {
                                    error_count++;
                                    CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用汇总状态更新失败，患者ID：{0}", model_costtotal.pid));
                                }
                            }

                            if (bll_costtotal.Add(model_costtotal))
                            {
                                success_count++;
                                CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用汇总操作成功，患者ID：{0}", model_costtotal.pid));
                            }
                            else
                            {
                                error_count++;
                                CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用汇总入库失败，患者ID：{0}"
                                     , model_costtotal.pid));
                            }

                        }
                        catch (Exception ex)
                        {
                            error_count++;
                            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU, string.Format("\r\n费用汇总入库异常，患者ID：{0},医院侧费用清单ID：{1}。失败原因{2}"
                                , model_costtotal.pid, model_costtotal.pid, ex.Message));
                            continue;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return error_count;
        }

        /// <summary>
        /// 获取一天的费用信息
        /// </summary>
        /// <param name="dt_source">数据源</param>
        /// <param name="day">要获取的日期</param>
        /// <returns></returns>
        private static DataTable GetCostList_OneDay(DataTable dt_source, string day)
        {
            DataTable dt_day = new DataTable();
            dt_day = dt_source.Clone(); // 克隆dt 的结构，包括所有 dt 架构和约束,并无数据； 
            DataRow[] rows = dt_source.Select(string.Format(" days= '{0}' ", day)); // 从dt 中查询符合条件的记录； 
            foreach (DataRow row in rows)  // 将查询的结果添加到dt中； 
            {
                dt_day.Rows.Add(row.ItemArray);
            }
            return dt_day;
        }
        #endregion
    }
}
